package cn.tedu.ivos.vehicle.service.impl;

import cn.tedu.ivos.vehicle.mapper.VehicleMapper;
import cn.tedu.ivos.vehicle.pojo.dto.VehicleQuery;
import cn.tedu.ivos.vehicle.pojo.dto.VehicleSaveParam;
import cn.tedu.ivos.vehicle.pojo.entity.Vehicle;
import cn.tedu.ivos.vehicle.pojo.vo.VehicleVO;
import cn.tedu.ivos.vehicle.service.VehicleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;

@Slf4j
@Service

public class VehicleServiceImpl implements VehicleService {
    @Autowired
    VehicleMapper vehicleMapper;
    /*根据条件搜索， 编辑车辆的详情信息（回显到表格中）  复用这个*/
    @Override
    public List<VehicleVO> selectVehicle(VehicleQuery vehicleQuery) {
        log.debug("查询车辆信息，参数：{}",vehicleQuery);
        List<VehicleVO> list = vehicleMapper.selectVehicle(vehicleQuery);
        return list;
    }

    //    添加车辆 、 编辑车辆（编辑后插入里面）
    @Override
    public void saveVehicle(VehicleSaveParam vehicleSaveParam) {
        Vehicle vehicle =new Vehicle();
        BeanUtils.copyProperties(vehicleSaveParam,vehicle);
        log.debug("保存车辆信息，参数：{}",vehicleSaveParam);
//        判断要进行插入还是更新操作
        if (vehicle.getId()==null){/*没id  新增*/
            vehicle.setCreateTime(new Date());
            vehicle.setStatus("1");//默认新增车辆状态为1
            vehicleMapper.insertVehicle(vehicle);
        }else {/*如果有id说明是更新操作*/
            vehicle.setUpdateTime(new Date());
            vehicleMapper.update(vehicle);
        }
    }

//    删除车辆操作：
    @Override
    public void deleteVehicle(Long vehicleId) {
        vehicleMapper.deleteVehicle(vehicleId);
    }

//    车辆管理的 解绑车辆
    @Override
    public void unbindVehicle(Long vehicleId) {
        log.debug("移除车辆：vehicleId{}",vehicleId);
        Vehicle vehicle = new Vehicle();
        vehicle.setId(vehicleId);/*设置车辆的id 也就是改那辆车的数据*/
        vehicle.setGeofenceBindStatus("0");/*解绑车辆 ；围栏的状态为0 注意是String类型*/
        vehicle.setGeofenceId(null);/*解绑车辆的围栏id 设置为null*/
        vehicle.setUpdateTime(new Date());/*车辆的更新时间*/
//        之前的更新SQL要求围栏编号不能为null 才会更新围栏编号
//        但此处由于业务=>将车辆与围栏解除绑定关系
//        需要将围栏编号设为null 所以需要写一个mapper层的方法
            vehicleMapper.updateNullValue(vehicle);
    }

    @Override
    public void bindVehicle(Long geofenceId, Long vehicleId) {
        log.debug("绑定车辆业务:geofenceId={},vehicleId={}",geofenceId,vehicleId);
        Vehicle vehicle = new Vehicle();
        vehicle.setId(vehicleId);
        vehicle.setGeofenceId(geofenceId);
        vehicle.setGeofenceBindStatus("1");
        vehicle.setUpdateTime(new Date());
        vehicleMapper.update(vehicle);
    }

}
